const path = require('path');
const fs = require('fs');
const jquery = require('cheerio');
const then = require('thenjs');
module.exports = class extends baseLogic {
    constructor() {
        super();

    }

    syncJsonFile(fileName) {
        let path = require('path');
        let fs = require('fs');
        let src=path.join(path.resolve(),"common","module","cms","config",`_${fileName}.json`);
        let target=path.join(path.resolve(),"common","module","cms","config",`${fileName}.json`);
        return new Promise((resolve, reject) => {
            fs.readFile(src, function (err, ret) {
                fs.writeFile(target, ret, function (err) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(true);
                    }
                })
            });
        });

    }


    getMarkoFiles(tempPath) {
        let files = [];
        let dirItems = fs.readdirSync(tempPath);
        dirItems.forEach(item => {
            if (item.indexOf('.marko') > -1 && item.indexOf('.js') == -1) {
                files.push(tempPath + '/' + item);
            } else {
                if (item.indexOf('.js') === -1) {
                    let _files = this.getMarkoFiles(tempPath + '/' + item);
                    if (_files.length > 0) {
                        files = files.concat(_files);
                    }
                }
            }
        });
        return files;
    }

    /**
     * 获取模板视图数据
     * @returns {Promise<*>}
     */
    async getTemplateViewData() {
        return new Promise((ok, wrong) => {
            let tmpViewData = {};//模板中的数据对象
            let siteInfo=JSON.parse(fs.readFileSync(path.join(path.resolve(),"common","module","cms","config","site-info.json")));
            let tempPath = path.resolve() + '/areas/home/static/template/' +siteInfo.siteTemplate + '/views';
            let markoFiles = this.getMarkoFiles(tempPath);

            then.eachSeries(markoFiles, (defer, file) => {
                log.debug(file);
                fs.readFile(file, (err, content) => {
                    content = content.toString();
                    if (content && content !== '') {
                        let $ = jquery.load(content);

                        $("[key]").each(function () {
                            let key = $(this).attr('key');
                            let type = $(this).attr('type');
                            if (type === 'text') {
                                tmpViewData[key] ={
                                    type:'text',
                                    value: $(this).text()
                                };
                            } else {
                                let model = $(this).attr();
                                tmpViewData[key] = model;
                            }


                        });
                        defer();
                    } else {
                        defer();
                    }
                })
            }).fin((defer, err , ret) => {
                if(err){
                    ok(null);
                }else{
                    ok(tmpViewData);
                }
            });
        })
    }

    async execTmpViewData() {
        let viewData = {};
        //---1 获取模板视图数据
        let tmpViewData = await this.getTemplateViewData();
        log.debug(tmpViewData);
        if(! tmpViewData) return null;
        //---2 是否存在 viewData.json
        let viewDataFilePath =path.join(path.resolve(),"common","module","cms","config","view-data.json") ;
        if (!fs.existsSync(viewDataFilePath)) {
            //不存在 说明这是第一次发布，直接复制tmpViewData变量中的数据到新文件view-data.json中
            viewData = tmpViewData;
            fs.writeFile(viewDataFilePath, JSON.stringify(tmpViewData));
        } else {
            //存在 说明这不是第一次发布，需要进行数据比对，在view-data.json中添加或移出tmpViewData中新增或移出的数据
            viewData = JSON.parse(fs.readFileSync(viewDataFilePath));
            let ver = this.webTools.common.UUID(8, 16);//创建数据版本
            for (let key in tmpViewData) {
                if (key) {
                    if (viewData[key]) {
                        viewData[key]._ver = ver;
                    } else {
                        viewData[key] = tmpViewData[key];
                        viewData[key]._ver = ver;
                    }
                }
            }
            //--移除弃用的属性
            for (let key in viewData) {
                if (!viewData[key]._ver || viewData[key]._ver !== ver) {
                    delete  viewData[key];
                }
            }
        }

        //---3 如果存在_view-data.json 说明前端页面在线编辑过，那么在生成view-data.json之后，需要用_view-data.json中数据更新view-data.json中的数据。更新完后删除_view-data.json
        let _viewDataFilePath = path.join(path.resolve(),"common","module","cms","config","_view-data.json");
        if (fs.existsSync(_viewDataFilePath)) {
            let _viewData = JSON.parse(fs.readFileSync(_viewDataFilePath));
            for (let key in _viewData) {
                if (key) {
                    viewData[key] = _viewData[key];
                }
            }
            fs.unlink(_viewDataFilePath);
        }
        fs.writeFile(viewDataFilePath, JSON.stringify(viewData));
        return viewData;
    }

    async publish() {
        await  this.execTmpViewData();
        await this.syncJsonFile('site-info');
        await this.syncJsonFile('mail');
        await this.syncJsonFile('script-code');
        delete require.cache[path.join(path.resolve(),"common","module","cms","config","site-info.json")];
        delete require.cache[path.join(path.resolve(),"common","module","cms","config","mail.json")];
        delete require.cache[path.join(path.resolve(),"common","module","cms","config","script-code.json")];
        delete require.cache[path.join(path.resolve(),"common","module","cms","config","view-data.json")];
        delete require.cache[path.join(path.resolve(),"common","module","cms","index")];
        return true;
    }

};
